class Solution:
    def longestValidParentheses(self, s: str) -> int:
        stack=[]
        i=0
        result=0
        deleted=[]
        if s=="":
            return 0
        while i<len(s) and s[i]==")":
            i+=1
        start=i
        last=0
        end=0
        while i<len(s):
            if s[i]=="(":
                if len(stack)!=0:
                    if i-stack[-1]-1>result:
                        result=i-stack[-1]-1
                else:
                    if len(deleted)!=0:
                        if i-deleted[-1]>result:
                            result=i-deleted[-1]
                stack.append(i)
            else:
                if len(stack)==0:
                    if len(deleted)!=0:
                        if i-deleted[-1]>result:
                            result=i-deleted[-1]
                    deleted=[]
                    end=i
                    start=i+1
                else:
                    l=stack.pop()
                    if not deleted or (deleted and l<deleted[-1]):
                        deleted.append(l)
            i+=1
        if len(stack)!=0:
            if len(s)-stack[-1]-1>result:
                return len(s)-stack[-1]-1
        if end<=start:
            end=len(s)
        if len(stack)==0 and end-start>result:
            return end-start
        return result

'''
执行用时：
64 ms
, 在所有 Python3 提交中击败了
21.60%
的用户
内存消耗：
15.1 MB
, 在所有 Python3 提交中击败了
39.62%
的用户
'''